package cn.ds.foodie.service.impl;

import cn.ds.foodie.constant.AliOssProp;
import cn.ds.foodie.service.IOssService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author laona
 * @decription oss
 * @since 2022-07-03 15:33
 **/
@Slf4j
@Service
public class OssServiceImpl implements IOssService {

    @Resource
    private AliOssProp aliOssProp;

    @Override
    public String upload(MultipartFile file, String userId, String fileExtName) throws IOException {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder()
                .build(aliOssProp.getEndPoint(),
                        aliOssProp.getAccessKeyId(),
                        aliOssProp.getAccessKeySecret());

        // 文件路径 + 文件名
        String objectName = aliOssProp.getObjectName() + "/" + userId + "/" + userId + "." + fileExtName;

        InputStream inputStream = file.getInputStream();
        // 存放到oss中
        ossClient.putObject(aliOssProp.getBucketName(), objectName, inputStream);
        ossClient.shutdown();

        return aliOssProp.getBucketEndPoint() + objectName;
    }
}
